<template>
  <view class="page">
    <view class="flex-col">
      <view class="header justify-between align-center">
        <view class="justify-between align-center">
          <image class="goodImg" mode="aspectFill" :src="good.imagelist && good.imagelist[0]" />
          <view class="goodTitle">
            {{ good.title }}
          </view>
        </view>
        <view v-if="userInfo.id != good.user_id">
          <view class="buyBtn" v-if="goodStatus.status == 0" @click="buyGood">确认入手</view>
          <view class="buyBtn pedding" v-if="goodStatus.status == 1"> 等待卖家确认 </view>
          <view class="buyBtn" @click="$to('/pages/evaluate/index?goodId=' + goodId + '&toUser=' + good.user_id)" v-if="goodStatus.status == 3">
            去评价
          </view>
          <view class="buyBtn pedding" v-if="goodStatus.status == 4"> 交易完成 </view>
        </view>
        <view v-if="userInfo.id == good.user_id">
          <view class="buyBtn" v-if="goodStatus.status == 0" @click="$to('/pages/publish/index?id=' + good.id)">管理</view>
          <view class="buyBtn" v-if="goodStatus.status == 1" @click="sellGood">确认出手</view>
          <view class="buyBtn" @click="$to('/pages/evaluate/index?goodId=' + goodId + '&toUser=' + good.user_id)" v-if="goodStatus.status == 3">
            去评价
          </view>
          <view class="buyBtn pedding" v-if="goodStatus.status == 4"> 交易完成 </view>
        </view>
      </view>

      <scroll-view scroll-y="true" class="scrollY" :scroll-into-view="sendetId" v-if="receivedMessages.length > 0">
        <view v-for="(item, index) in receivedMessages" :key="index" :id="'scrollIndex' + index">
          <!-- 左边 -->
          <view class="line align-center justify-start" v-if="room.myself.id != item.sender.id">
            <image class="avatarImg" mode="aspectFill" :src="item.sender.avatar" />

            <view class="otherContent flex-col" v-if="!item.type" style="border-radius: 0px 12px 12px 12px">
              <view class="contentTxtStyle" v-if="!item.content.url">{{ item.content.body }}</view>
              <image class="video" mode="widthFix" :src="item.content.url" v-if="item.content.url && !item.content.url.endsWith('.mp4')" />
              <view class="videoPopu" v-if="item.content.url && item.content.url.endsWith('.mp4')">
                <view v-if="item.content.videoImg" @click="openVideo(item.content.url)">
                  <image class="video" mode="widthFix" :src="item.content.videoImg" />
                  <image class="previewPlay" mode="widthFix" src="../../static/img/play.png" />
                </view>
                <uv-loading-icon v-if="item.content.videoImg == ''" class="mt20" :size="30"></uv-loading-icon>
              </view>
            </view>
            <view class="otherContent" v-if="item.type == 'user'">
              <view class="">{{ item.sender.id != good.user_id ? '入手方' : '出手方' }}信息</view>
              <view class="mt5">姓名：{{ item.username }}</view>
              <view class="mt5">电话：{{ item.mobile }}</view>
            </view>
            <view class="otherContent align-center" v-if="item.type == 'address'">
              <view class="contentTxtStyle" style="max-width: 85%">{{ item.content }}</view>
              <image class="mapImg ml10" src="../../static/chat/map.png" />
            </view>
            <view class="evaluate" v-if="item.type == 'userEvaluate'">
              <view class="evaluate-title">{{ item.sender.id == good.buyer ? '买家' : '卖家' }}完成了评价</view>
              <view class="evaluate-text">{{ item.content }}</view>
              <uni-rate v-model="item.star" disabledColor="#ffca3e" disabled class="evaluate-start" />
            </view>
          </view>
          <!-- 右边 -->
          <view class="line align-center justify-end" v-if="room.myself.id == item.sender.id">
            <view class="userContent flex-col" v-if="!item.type">
              <view class="contentTxtStyle" v-if="!item.content.url">{{ item.content.body }}</view>
              <image class="video" mode="widthFix" :src="item.content.url" v-if="item.content.url && !item.content.url.endsWith('.mp4')" />
              <view class="videoPopu" v-if="item.content.url && item.content.url.endsWith('.mp4')">
                <view v-if="item.content.videoImg" @click="openVideo(item.content.url)">
                  <image class="video" mode="widthFix" :src="item.content.videoImg" />
                  <image class="previewPlay" mode="widthFix" src="../../static/img/play.png" />
                </view>
                <uv-loading-icon v-if="item.content.videoImg == ''" class="mt20" :size="30"></uv-loading-icon>
              </view>
            </view>
            <view class="userContent align-center" v-if="item.type == 'address'">
              <image class="mapImg mr10" src="../../static/chat/map.png" />
              <view class="contentTxtStyle" style="max-width: 85%">{{ item.content }}</view>
            </view>
            <view class="userContent" v-if="item.type == 'user'">
              <view class="">{{ userInfo.id != good.user_id ? '入手方' : '出手方' }}信息</view>
              <view class="mt5">姓名：{{ item.username }}</view>
              <view class="mt5">电话：{{ item.mobile }}</view>
            </view>
            <view class="evaluate" style="background-color: rgba(255, 242, 243, 1)" v-if="item.type == 'userEvaluate'">
              <view class="evaluate-title" style="color: rgba(254, 55, 60, 1)">{{ item.sender.id == good.buyer ? '买家' : '卖家' }}完成了评价</view>
              <view class="evaluate-text" style="color: rgba(254, 55, 60, 1)">{{ item.content }}</view>
              <uni-rate v-model="item.star" disabledColor="#ffca3e" disabled class="evaluate-start" />
            </view>
            <image class="avatarImg" referrerpolicy="no-referrer" mode="aspectFill" :src="item.sender.avatar" />
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="footer">
      <view class="footContent justify-between align-center">
        <view class="footIpt justify-between">
          <input type="text" style="width: 88%" placeholder="我来说两句" v-model="otherContent" @confirm="userSend" />
          <image @click="userSend" class="sendImg" src="/static/chat/s.png" />
        </view>
        <image class="addVidoe" src="/static/chat/j.png" @click="selectMediaType" />
        <image src="/static/chat/add2.png" class="addVidoe" @click="sendAddress" />
        <!-- <image src="/static/chat/add2.png" class="addVidoe" @click="sendUser" /> -->
      </view>
    </view>
  </view>
</template>
<script>
import { getUser } from '../../utils/auth.js';

export default {
  data() {
    return {
      ws: null, // WebSocket 实例
      messageInput: '', // 用户输入的消息
      receivedMessages: [], // 接收到的消息列表
      otherContent: '',
      room: {},
      good: {},
      sednVideoUrl: '',
      scrollTop: 0,
      sendetId: '1',
      goodStatus: { status: '' },
      user_id: '',
      goodId: '',
      userInfo: {}
    };
  },
  onShow() {
    if (this.sideId) {
      this.getData();
    }
  },
  onLoad(opt) {
    this.buy_user_id = opt.user_id;
    this.sideId = opt.user_id;
    this.goodId = opt.goodId;
    this.init();
    this.userInfo = getUser();
  },
  methods: {
    sendUser() {
      this.sendMessage('m.text', `type=user&mobile=${this.userInfo.mobile}&username=${this.userInfo.real_name}`);
    },
    openVideo(url) {
      uni.navigateTo({
        url: '/pages/test/videoPaly?url=' + url,
        animationType: 'slide-in-bottom',
        animationDuration: 200
      });
    },
    init() {
      this.$http({ url: 'getArticleDetail', method: 'GET', data: { id: this.goodId } }).then((res) => {
        this.good = res.data;
        let data = {
          article_id: this.goodId
        };
        if (this.userInfo.id == this.good.user_id) {
          data.buy_user_id = this.buy_user_id;
        }
        this.$http({ url: 'getArticleStatus', data }).then((res) => {
          this.goodStatus = res.data;
        });
      });
    },
    sendAddress() {
      const address = uni.getStorageSync('wxAdd');
      if (!address.address) {
        return uni.showToast({
          title: '请检查位置权限是否打开',
          icon: 'none'
        });
      }
      this.sendMessage('m.text', `type=address&content=${address.address}`);
    },
    sendMessage(type, data, url) {
      let obj = {
        type: 'send',
        from_user: this.room.myself.id, // 发起者用户ID
        to_user: this.room.seller.id, //接收者ID
        msg_type: type,
        data: data,
        good_id: this.goodId
      };
      if (url) {
        obj.url = url;
      }
      this.ws.send({
        data: JSON.stringify(obj)
      });
    },
    selectMediaType() {
      var that = this;
      uni.showActionSheet({
        itemList: ['上传图片', '上传视频'],
        success: function (res) {
          if (res.tapIndex === 0) {
            that.selectImage();
          } else if (res.tapIndex === 1) {
            that.selectVideo();
          }
        }
      });
    },
    selectImage() {
      uni.chooseImage({
        count: 1, //默认9
        sourceType: ['camera', 'album'],
        success: (res) => {
          console.log(res);
          uni.uploadFile({
            url: 'http://wuhu.njwhd.com/api/common/upload', //仅为示例，非真实的接口地址
            filePath: res.tempFilePaths[0],
            name: 'file',
            success: (uploadFileRes) => {
              let res = JSON.parse(uploadFileRes.data);
              this.sednVideoUrl = res.data.url;
              this.sendMessage('m.file', '发送图片', res.data.url);
            }
          });
        }
      });
    },
    selectVideo() {
      uni.chooseVideo({
        sourceType: ['camera', 'album'],
        success: (res) => {
          uni.uploadFile({
            url: 'http://wuhu.njwhd.com/api/common/upload', //仅为示例，非真实的接口地址
            filePath: res.tempFilePath,
            name: 'file',
            success: (uploadFileRes) => {
              let res = JSON.parse(uploadFileRes.data);
              this.sednVideoUrl = res.data.url;
              this.$http({
                url: 'upLoadFile',
                data: { file: res.data.url }
              }).then((res) => {
                this.sendMessage('m.file', '发送视频', res.data.url + ',' + res.data.screen_shots_pic_url);
              });
            }
          });
        }
      });
    },

    getData() {
      this.$http({
        url: 'getUserInfo?user_id=' + this.sideId
      }).then((res) => {
        this.room = res.data;
        uni.setNavigationBarTitle({
          title: this.room.seller.nickname
        });
        this.connectToWs();
      });
    },
    userSend() {
      if (this.otherContent) {
        this.sendMessage('m.text', this.otherContent);
        this.otherContent = ''; // 清空输入框
      }
    },
    buyGood() {
      uni.showModal({
        title: '提示',
        content: '请确认开始交易',
        success: (res) => {
          if (res.confirm) {
            this.sendUser();
            this.$http({
              url: 'dealIn',
              data: {
                article_id: this.good.id
              }
            }).then((res) => {
              this.init();
            });
          }
        }
      });
    },
    sellGood() {
      uni.showModal({
        title: '提示',
        content: '请确认是否出手',
        success: (res) => {
          if (res.confirm) {
            this.sendUser();

            this.$http({
              url: 'dealOut',
              data: {
                article_id: this.good.id,
                buy_user_id: this.room.seller.id
              }
            }).then((res) => {
              this.init();
            });
          }
        }
      });
    },
    connectToWs() {
      this.ws = uni.connectSocket({
        url: 'ws://1.13.195.104:7788',
        success: () => {
          console.log('成功');
        }
      });

      this.ws.onOpen(() => {
        this.ws.send({
          data: JSON.stringify({
            type: 'init',
            from_user: this.room.myself.id, // 发起者用户ID
            to_user: this.room.seller.id, //接收者ID
            good_id: this.goodId
          })
        });
      });
      this.ws.onMessage((event) => {
        this.init();
        let data = JSON.parse(event.data);
        if (data.type == 'connected') return;
        if (data.type == 'ping') return;

        if (data.type == 1) {
          this.receivedMessages = this.assembleData(data.data);
        } else {
          this.receivedMessages.push(...this.assembleData(data));
        }
        setTimeout(() => {
          this.sendetId = 'scrollIndex' + String(this.receivedMessages.length - 1);
        }, 200);
      });

      this.ws.onError = (error) => {
        this.connectToWs();
        uni.showModal({
          content: JSON.stringify(error),
          title: 'WebSocket 错误'
        });
      };

      this.ws.onClose = (event) => {
        this.connectToWs();
      };
    },
    assembleData(arr) {
      return arr.map((el) => {
        if (el.content.body == '发送视频') {
          let arr = el.content.url.split(',');
          el.content.url = arr[0];
          el.content.videoImg = arr[1];
        }
        if (el.content.body.includes('type=')) {
          let obj = this.getParamsObj(el.content.body);
          el = Object.assign(el, obj);
        }
        return el;
      });
    },
    getParamsObj(str) {
      let queryString = str;
      let params = queryString.split('&').reduce((acc, current) => {
        let [key, value] = current.split('=');
        acc[key] = value;
        return acc;
      }, {});
      return params;
    }
  }
};
</script>
<style lang="scss" scoped>
@import '../common/common.css';
.videoPopu {
  position: relative;
  .previewPlay {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 50px;
    height: 50px;
    display: block;
    transform: translateX(-50%) translateY(-50%);
  }
}
.page {
  background-color: #fff;
  position: relative;
  width: 750rpx;
  height: 93vh;
  overflow: hidden;
}

.evaluate {
  width: 200px;
  background: #f8f8f8;
  border-radius: 12px 0px 12px 12px;
  padding: 20px;
  margin-right: 10px;
  .evaluate-title {
    font-weight: 500;
    font-size: 15px;
    color: #333333;
    padding-bottom: 5px;
    border-bottom: 1px solid #eeeeee;
  }
  .evaluate-text {
    font-size: 12px;
    color: #999999;
    line-height: 18px;
    margin-top: 5px;
  }
  .evaluate-start {
    margin-top: 10px;
  }
}

.header {
  background-color: rgba(248, 248, 248, 1);
  width: 100%;
  padding: 24rpx 40rpx 26rpx 40rpx;
  margin-bottom: 10px;
  height: 10vh;
}

.goodImg {
  width: 110rpx;
  height: 110rpx;
  border-radius: 10px;
  display: block;
  margin-right: 10px;
}

.goodTitle {
  color: rgba(51, 51, 51, 1);
  font-size: 26rpx;
  width: 200px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.avatarImg {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 10rpx;
  border-radius: 50%;
}

.line {
  margin-top: 22px;
  width: 100%;
  display: flex;
  padding-right: 22px;
  font-size: 30rpx;
  padding-left: 22px;
  .otherContent {
    background-color: rgba(248, 248, 248, 1);
    border-radius: 0px 12px 12px 12px;
    padding: 10px;
    max-width: 80%;
    margin-left: 10px;
    text-wrap: wrap;
    box-sizing: border-box;
  }
  .userContent {
    background-color: rgba(255, 242, 243, 1);
    color: rgba(254, 55, 60, 1);
    border-radius: 12px 0px 12px 12px;
    margin-right: 10px;
    align-items: center;
    padding: 10px;
    box-sizing: border-box;
    max-width: 80%;
  }
  .mapImg {
    width: 30px;
    height: 30px;
    display: block;
  }
}

.footer {
  background: #fff;
  width: 100%;
  margin-top: -2rpx;
  padding: 20rpx 20rpx 16rpx 20rpx;
  position: fixed;
  bottom: 2vh;
  left: 0;
  z-index: 999;
  height: 6vh;
  .footContent {
    width: 100%;
    .footIpt {
      background-color: rgba(246, 246, 249, 1);
      border-radius: 20px;
      width: 80%;
      padding: 5px;
      padding-left: 10px;
      align-items: center;
      input {
        font-size: 30rpx;
        height: 35px;
      }
    }
  }
  .sendImg {
    width: 56rpx;
    height: 56rpx;
    display: block;
  }

  .addVidoe {
    width: 60rpx;
    height: 60rpx;
    margin: 8rpx 0 4rpx 0;
  }
}

.chunk {
  display: flex;
  margin-top: 10px;
}
.chunkItem {
  width: 21%;
  font-size: 12px;
  height: 60px;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
  .text {
    width: 100%;
  }
  image {
    width: 30px;
    height: 30px;
    display: block;
    margin: 0 auto;
  }
}
.scrollY {
  height: 75vh;
}
.video {
  width: 200px;
}
.buyBtn {
  height: 30px;
  background: linear-gradient(331deg, #fe373c 0%, #fe7837 100%);
  box-shadow: 0px 2px 6px 0px rgba(255, 136, 139, 0.5);
  border-radius: 15px;
  font-weight: 500;
  font-size: 12px;
  color: #ffffff;
  line-height: 30px;
  padding: 0 5px;
  width: 70px;
  text-align: center;
}
.pedding {
  background: gray;
  color: #fff;
  box-shadow: none;
  width: 90px;
}
</style>
